package xyz.liut.liutlibraries;

import android.os.Handler;
import android.os.Message;

/**
 * Created by liut_ on 2016/5/10.
 */
public class DingSrwThreadsUtil {

    private final OnFinishListener listener;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String time = (String) msg.obj;
            switch (msg.what) {
                case 0:
                    //正在倒计时
                    listener.onRunning(time);
                    threadRun();
                    break;
                case 1:
                    //倒计时结束
                    listener.onFinsh(time);
                    break;
            }
        }
    };

    private Runnable r = new Runnable() {
        @Override
        public void run() {
            try {
                Thread.sleep(9);
                Message message = handler.obtainMessage();
                message.what = 0;

                //当前时间
                String timeNow = LiutUtils.getTime();
                String timeLong = System.currentTimeMillis() + "";
                int nowMin = Integer.parseInt(timeNow.substring(14, 16));


                //分、秒、毫秒
                int min = 9 - nowMin % 10;
                int sec = 59 - Integer.parseInt(timeNow.substring(17, 19));
                int msec = 99 - Integer.parseInt(timeLong.substring(timeLong.length() - 3, timeLong.length() - 1));


                //优化后的分、秒、毫秒
                String sMin;
                if (min < 10) {
                    sMin = "0" + min;
                } else {
                    sMin = min + "";
                }

                String sSec;
                if (sec < 10) {
                    sSec = "0" + sec;
                } else {
                    sSec = sec + "";
                }

                String sMsec;
                if (msec < 10) {
                    sMsec = "0" + msec;
                } else {
                    sMsec = msec + "";
                }

                if (min == 0 && sec == 0) {
                    message.what = 1;
                    sMsec = "00";
                }

                //输出
                message.obj = sMin + ":" + sSec + ":" + sMsec;
                message.sendToTarget();
            } catch (InterruptedException e) {
                threadRun();
            }
        }
    };

    public DingSrwThreadsUtil(OnFinishListener listener) {
        this.listener = listener;
    }


    public void threadRun() {
        new Thread(r).start();
    }

    public void stop() {
        r = null;
    }

    public interface OnFinishListener {
        void onRunning(String time);

        void onFinsh(String time);
    }

}
